local desc_wdtx_mode = [[
  # 问鼎天下简介
  ___

  肉鸽构建卡牌与三国杀玩法相结合。以构筑卡组为核心机制玩法。该模式仅限玩家一人。烧条时间改为60s最佳。

  游戏机制：
  
    游戏开始。玩家拥有【抽】标记的私人牌堆且【问鼎天下】卡组加入此牌堆。你摸牌只能从此卡组摸牌（回合结束时会从”弃“牌堆加入“抽”牌堆洗牌）。每当从战斗外的机制（剧情，商店，宝箱等等）获得卡牌都会进入此牌堆。
    
    战斗中每当有牌进入弃牌堆，其中包含此卡组的牌则会进入玩家【弃】标记私人牌堆。

  卡牌构筑：

    初始牌组为军八卡组（闪电，连弩除外），大部分卡牌（一些装备除外）可以通过模式机制升级（升级机制看卡牌说明）
  
  地图剧情：
  
    生成随机的剧情事件。包含战斗，开宝箱，商店。其他子事件。

]]
local WdtxObj = require "packages/wdtx/WdtxObj"
local Story = require "packages/wdtx/Story"
local WD = require "packages/wdtx/WdtxData"
local MobileSelGenMuty = require "packages/wdtx/MobileSelGenMuty"

--开启测试
local IStest
-- local IStest
--开启测试AI武将
local IStestAI = false
--玩家测试武将
local TESTgen = "mouxusheng"
--测试AI武将（避免自由选）
local TESTgens = {"guozhao","m_ex__liaohua","zhangfen","xielingyu","zhouyi","ol__tengfanglan","dongyun","l__zhangliao","ex__simayi","ol_ex__zhangjiao","ty_ex__zhuran","l__lvbu","ty__yanghu","zhaotongzhaoguang","joy__xunyou","miniex__huangyueying","ty__yanghu","joy__xunyou","godzhaoyun","js__guanyu","lvlingqi","dukui","ty_ex__wuyi","ol_ex__sunjian","xizhicai","qinmi","godganning","ty__chenlin","ex__ganning","yuejiu","caomao","ty__lidian","ol__luyusheng","godganning","ty_ex__caozhi","zhaotongzhaoguang"}
--过滤其他卡组（只允许白名单的卡组加入牌堆）
local WHILEcards = {"standard","standard_cards","maneuvering","lang_cards","tenyear_token","mobile_derived","ol_token","overseas_token"}
--保留玩家本模式重要的标记
-- local SAVEmarks = {"curlayerphase","@slash_dmg","@trick_dmg","@pdlbox","@gold_num","@df_lingxin","@shieldnum","@slash_num"}

--初始化游戏对象
local initGameObj = function(player)
  --初始化游戏数据
  local initGameData = {
    storyid = 1,
    endstoryid = 2,
    upcards = WD:getCanUpCards(),
    costcards = WD:getCostCardsData(),
    batsetmentdata = WD:getBatSetmentData(),
    boxdata = WD:getBoxData(),
    shopdata = WD:getShopData(),
    battledata = WD:getBattleData(),
    othereventdata = WD:getOtherEventData(),
    mapdata = WD:getInitMapData(),
    
    storyinfo = {
      events = {"beginAdventure"},--剧情列表
      dialogconfig = {
        {
          {dialog = {{talkers={1,"hxfc_author",2,player.general},say="欢迎来到问鼎天下，此刻你拥有问鼎卡组（点你武将面板的”摸“可观看）。你摸牌只能从此卡组摸牌（卡组摸完下回合开始会从”弃“牌堆加入洗牌），进入弃牌堆的牌（涉及此卡组的牌）会进入你面板”弃“牌堆。此卡组牌能够升级关键时候助你一臂之力。长路漫漫，选一个奖励去冒险吧。"}},--对话内容：talkers的索引第1和第3值分别是对应剧情左右将卡位置（1为左，2为右）。索引第2和第4值分别是对应g该位置上将名。默认从索引1的将卡位置开始说话，say为说话内容
            choices = {"技能4选1","升级2张牌","获得15金币","移除3张牌","从4张牌选2张加入卡组"}, --选项，每段剧情至少有个选项，Story.ContinueStory为”继续“选项，同理Story.NextStory为”下一章“选项
            eventchc = {1,1,1,1,1}
          },
        },
      },
    },
    -- chcskills = {{"gongjian","ex__zhiheng","ex__jianxiong","ex__yiji","leiji","ex__fankui","yuandi","jiexing","suifu","ty__canshi","huayi","souying","pingxi","renzheng","ty__songci","ty__wenji","huace","daoshu"},
    -- {"jishan","zhenqiao","pingtao","juelie","yiyong","suchou","xinyou","fangdu","fengyan","shiyuan","qianlong","huayi","caizhuang","mansi","zhaowen","jingzao","jinjian","poyuan","ty__benyu_active"}}
  }
  player.room:addPlayerMark(player,"@gold_num",IStest and 900 or 10)
  player.room.logic.Wdtx = WdtxObj:new(player,initGameData) --注册一个问鼎天下对象
end

---@return boolean
local function execGameEvent(tp, ...)
  local event = tp:create(...)
  local _, ret = event:exec()
  return ret
end

local wdtx_getLogic = function()
  local wdtx_logic = GameLogic:subclass("wdtx_logic")

  function wdtx_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      { "lord" },
      { "lord", "rebel" },
      { "lord", "rebel", "rebel" },
      { "lord", "rebel", "rebel", "rebel" },
      { "lord", "rebel", "rebel", "rebel", "rebel" },
      { "lord", "loyalist", "loyalist", "loyalist", "rebel", "rebel" },
      { "lord", "rebel", "rebel", "rebel", "rebel", "rebel", "rebel" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "loyalist", "loyalist" },
    }
  end

  function wdtx_logic:action()
    self:trigger(fk.GamePrepared)
    local room = self.room

    while true do
      execGameEvent(GameEvent.Round)
      if room.game_finished then break end
    end
  end

  function wdtx_logic:prepareForStart()
    local room = self.room
    local players = room.players
    self:addTriggerSkill(Fk.skills["game_rule"] --[[@as TriggerSkill]])
    for _, trig in ipairs(Fk.global_trigger) do
      if trig:getSkeleton().name ~= "mobile_effect" then  --关闭手杀特效
        self:addTriggerSkill(trig)
      end
    end
    -- for _, trig in ipairs(Fk.legacy_global_trigger) do
    --   self:addTriggerSkill(trig)
    -- end
    self.room:sendLog{ type = "$GameStart" }
    self.room:sendLog{ type = "#wdtx_gamestart" , toast = true }
    self.room:setBanner("@[:]wdtx_mode-intro","wdtx-intro")
  end

  function wdtx_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    table.shuffle(roles)
    local bots_t = {}
    local players_t = {}
    for i = 1, n do
      local p = room.players[i]
      if p.id < 0 then
        table.insert(bots_t,{p.id,i})
      else
        table.insert(players_t,{p.id,i})
      end
    end
    local randplayer = room.players[table.random(players_t)[2]]
    randplayer.role = "lord"
    randplayer.role_shown = true
    room:broadcastProperty(randplayer, "role")

    for i = 1, n do
      local p = room.players[i]
      if p.role ~= "lord" then
        p.role = p.id < 0 and "rebel" or "loyalist"
        p.role_shown = true
        room:broadcastProperty(p,"role")
      end
    end
  end

  function wdtx_logic:chooseGenerals()
    local room = self.room
    local generalNum = room:getSettings("generalNum")
    local n = room:getSettings("enableDeputy") and 2 or 1
    local lord = room:getLord()
    if not lord then
      lord = room.players[1]
    end
    room:setCurrent(lord)
    local nonlord = room:getOtherPlayers(lord)
    local players = room.players

    MobileSelGenMuty:new({
      generalNum = 8,
      repcount = 1,
      istest = IStest,
      closeskin = true,
      jumpsysaipool = true,
      genpoolname = "MN_XLKJ",
      aipoolname = "WDTX"
    })

    room:askToChooseKingdom({lord})
    room:broadcastProperty(lord, "kingdom")

    initGameObj(lord)
  end
  return wdtx_logic
end

Fk:addMiniGame {
  name = "ChooseGeneralWithCanChangeForWDTX",
  qml_path = "packages/wdtx/qml/ChooseGeneralWithCanChange",
  default_choice = function(player, data) --默认值
    return table.random(data.cards, data.num)
  end,
  update_func = function(player, data)
    player:doNotify("UpdateMiniGame", data)
  end,
}


local wdtx_mode = fk.CreateGameMode{
  name = "wdtx_mode",
  minPlayer = 5,
  maxPlayer = 5,
  rule = "#wdtx_rule",
  logic = wdtx_getLogic,
  build_draw_pile = function(self)
    local filterCardIds = {}
    local void = {}
    local excepts = {"savage_assault","collateral","archery_attack","crossbow","lightning"} -- 删除一些卡组
    local allCardIds = Fk:getAllCardIds()
    for i = 1, #allCardIds do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived then
          -- table.removeOne(allCardIds, id)
          table.insert(void, id)
        else
          if table.contains(WHILEcards,card.package.name) then
            if not table.contains(excepts,card.trueName) then
              table.insert(filterCardIds,id)
            end
            if WD:getInitCards()[card.name] then
              -- table.removeOne(allCardIds, id)
              table.insert(void, id)
            end
          end
        end
      end
    end
    return filterCardIds, void
  end,
  winner_getter = function(self, victim)
    if not victim.surrendered and victim.rest > 0 then
      return ""
    end
    local room = victim.room
    local alive = table.filter(room.players, function(p) ---@type Player[]
      return not p.surrendered and not (p.dead and p.rest == 0)
    end)
    if #alive == 0 then
      return ""
    end
    local winner = alive[1].role
    for _, p in ipairs(alive) do
      if p.role ~= winner then
        return ""
      end
    end
    return winner
  end,
  surrender_func = function(self, playedTime)
    return { { text = "你可以随时投降。", passed = true } }
  end,
}

Fk:loadTranslationTable{
  ["@[:]wdtx_mode-intro"] = "模式",
  ["wdtx-intro"] = "问鼎天下(点击查看)",
  [":wdtx-intro"] =  "<br>肉鸽构建卡牌与三国杀玩法相结合。以构筑卡组为核心机制玩法。该模式仅限玩家一人。烧条时间改为60s最佳。\
  <br>游戏机制：\
  <br>游戏开始。玩家拥有【抽】标记的私人牌堆且【问鼎天下】卡组加入此牌堆。你摸牌只能从此卡组摸牌（回合结束时会从”弃“牌堆加入“抽”牌堆洗牌）。\
  <br>每当从战斗外的机制（剧情，商店，宝箱等等）获得卡牌都会进入此牌堆。\
  <br>战斗中每当有牌进入弃牌堆，其中包含此卡组的牌则会进入玩家【弃】标记私人牌堆\
  <br>卡牌构筑：<br>初始牌组为军八卡组（闪电，连弩除外），大部分卡牌（一些装备除外）可以通过模式机制升级（升级机制看卡牌说明）\
  <br>地图剧情：<br>生成随机的剧情事件。包含战斗，开宝箱，商店。其他子事件。",

  ["#wdtx_gamestart"] = "提示：请保证<b>仅开启军争卡组</b>",
  ["hxfc_author"] = "幻想风车",
  ["author_says"] = "前言",
  ["wdtx_mode"] = "问鼎天下",
  ["#wdtx_rule"] = "问鼎天下",
  ["#wdtx_modskill"] = "",
  ["@gold_num"] = "币:",
  -- [":wdtx_modskill"] = "你摸牌只从“抽卡区”摸牌，进入弃牌堆中的牌包含有你“抽卡区”的牌则进入你的“弃卡区”",
  ["self_draws"] = "抽:",
  ["self_discs"] = "弃:",
  ["self_cost"] = "墓:",
  ["selgold"] = "拿%arg币",
  ["rec_hp"] = "回复%arg体力",

  ["shop"] = "商店",
  ["Exist"] = "离开",
  ["entershop"] = "进入商店",
  ["buyskills"] = "购买技能",
  ["buycards"] = "购买卡牌",
  ["uplvcards"] = "升1张牌(需%arg币)",
  ["forgetcards"] = "丢1张牌(需%arg币)",

  ["map_select"] = "地图选择",

  -- ["randomskill_4_1"] = "初入乱世",
  ["wdtx_rewardchc"] = "选择两项奖励",

  ["meetHuangJin"] = "路遇黄巾",
  ["saveGuanZhang"] = "关张奋战",
  
  ["recoverall"] = "治愈",
  [":recoverall"] = "恢复全部体力",

  -- ["self_draws"] = "抽卡区",
  -- ["self_discs"] = "弃卡区",
  -- ["emy_atk_cards"] = "进攻意图",

  ["@up_damage"] = "伤害+",
  ["@up_strongmark"] = "重伤+",
  ["@up_weakmark"] = "虚弱+",
  ["@up_defmark"] = "护甲+",
  ["@up_shdmgmark"] = "盾杀+",
  ["@up_likeslashmark"] = "杀牌-",
  ["@sub_cost"] = "费-",
  ["@up_drawmark"] = "抽卡+",
  ["@up_atknum"] = "次数+",
  ["@@up_equipall"] = "升级手牌",
  ["@up_power"] = "力量+",

  ["beginAdventure"] = "问鼎天下",
  -- ["againOnce"] = "再来一次",
  ["normonster"] = "普通怪",
  ["elitemonster"] = "精英怪",
  ["box"] = "宝箱",
  ["boss"] = "BOSS",
  ["rest"] = "休息",
  ["otherevents"] = "？？",

  [":wdtx_mode"] = desc_wdtx_mode,
}

return wdtx_mode
